package in.developersguide.jms.suntm;

import java.util.Hashtable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class HelloWorldJMS {

	public static void main(String[] args) {
	   ConnectionFactory connectionFactory = null;
	   Queue myQueue;
	   
  try {
	  
	  String MYCF_LOOKUP_NAME = "myConnection";
      String MYQUEUE_LOOKUP_NAME = "sunmq";
      
      Hashtable env;
      Context ctx = null;

      env = new Hashtable();
      
      
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
      env.put(Context.PROVIDER_URL, "file:///C:/mq");
      ctx = new InitialContext(env);
      connectionFactory = (javax.jms.ConnectionFactory)ctx.lookup(MYCF_LOOKUP_NAME);
      myQueue = (javax.jms.Queue)ctx.lookup(MYQUEUE_LOOKUP_NAME);
      
		//connectionFactory = new com.sun.messaging.ConnectionFactory();
		Connection myConn = connectionFactory.createConnection();
		Session mySess = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		//myQueue = new com.sun.messaging.Queue("world");
		MessageProducer myMsgProducer = mySess.createProducer(myQueue);
		
		TextMessage myTextMsg = mySess.createTextMessage();
        myTextMsg.setText("Hello World");
        System.out.println("Sending Message: " + myTextMsg.getText());
        myMsgProducer.send(myTextMsg);
        
        MessageConsumer myMsgConsumer = mySess.createConsumer(myQueue);
        myConn.start();
        Message msg = myMsgConsumer.receive();
		
        if (msg instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) msg;
            System.out.println("Read Message: " + txtMsg.getText());
        }
        
        mySess.close();
        myConn.close();
		
	} catch (JMSException e) {
		 e.printStackTrace();
	} catch (NamingException e) {
		e.printStackTrace();
	}

	}

}
